package com.demo.websocketbarrage.controller;
import cn.hutool.json.JSONObject;
import com.demo.websocketbarrage.entity.Greeting;
import com.demo.websocketbarrage.entity.HelloMessage;
import com.demo.websocketbarrage.entity.PlayerSiteCommand;
import com.demo.websocketbarrage.entity.Site;
import com.demo.websocketbarrage.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.websocket.Session;
import java.util.HashMap;

@Controller
public class GreetingController {

    @Autowired
    GameService gameService;

    HashMap<String,Site> gameSiteData=new HashMap<>();


    @MessageMapping("/playersite")
    @SendTo("/topic/siteMove")
    public HashMap<String,Site> siteMove(PlayerSiteCommand playerSiteCommand) throws Exception {
        synchronized (gameSiteData){
            gameSiteData=gameService.executePlayerSiteCommand(gameSiteData,playerSiteCommand);
        }
        return gameSiteData;
    }





    /**
     * 用户问好
     * @return
     * @throws Exception
     */
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")//发送到
    public Greeting greeting(HelloMessage message) throws Exception {
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }


    @Autowired
    SimpMessagingTemplate msgTemp;

    @GetMapping("serverSendMsg")
    @ResponseBody
    public void serverSendMsg(){
        Greeting greeting = new Greeting("来自服务器的消息");
        msgTemp.convertAndSend("/topic/greetings",greeting);
    }





}
